using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Threading;

using SpringProxAPI;
using SproxDesFireAPI;


namespace SproxTool
{
  public class fMain:System.Windows.Forms.Form
  {
    private bool ReaderActive = false;
    private bool ReaderPaused = false;

#region Windows Form Design

      private System.Windows.Forms.TextBox eStatus;
  	private System.Windows.Forms.Button btnOpenClose;
  	private System.Windows.Forms.Button btnPauseResume;
  	private System.Windows.Forms.Button btnInfos;
  	private System.Windows.Forms.TextBox mDialog;
  	private System.Windows.Forms.Button btnClear;
    private System.Windows.Forms.Timer tmrWork;
    private System.Windows.Forms.CheckBox cbPolling;
    private System.Windows.Forms.CheckBox cbTCL;
      private PictureBox branded;
      private Label lbDesc;
      private PictureBox header;

    private void InitializeComponent()
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(fMain));
        this.eStatus = new System.Windows.Forms.TextBox();
        this.btnOpenClose = new System.Windows.Forms.Button();
        this.btnPauseResume = new System.Windows.Forms.Button();
        this.btnInfos = new System.Windows.Forms.Button();
        this.mDialog = new System.Windows.Forms.TextBox();
        this.btnClear = new System.Windows.Forms.Button();
        this.cbPolling = new System.Windows.Forms.CheckBox();
        this.cbTCL = new System.Windows.Forms.CheckBox();
        this.tmrWork = new System.Windows.Forms.Timer();
        this.header = new System.Windows.Forms.PictureBox();
        this.branded = new System.Windows.Forms.PictureBox();
        this.lbDesc = new System.Windows.Forms.Label();
        // 
        // eStatus
        // 
        this.eStatus.BackColor = System.Drawing.SystemColors.Control;
        this.eStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))));
        this.eStatus.Location = new System.Drawing.Point(-1, 248);
        this.eStatus.ReadOnly = true;
        this.eStatus.Size = new System.Drawing.Size(168, 19);
        // 
        // btnOpenClose
        // 
        this.btnOpenClose.Location = new System.Drawing.Point(3, 31);
        this.btnOpenClose.Size = new System.Drawing.Size(52, 20);
        this.btnOpenClose.Text = "Open";
        this.btnOpenClose.Click += new System.EventHandler(this.btnOpenClose_Click);
        // 
        // btnPauseResume
        // 
        this.btnPauseResume.Enabled = false;
        this.btnPauseResume.Location = new System.Drawing.Point(59, 31);
        this.btnPauseResume.Size = new System.Drawing.Size(52, 20);
        this.btnPauseResume.Text = "Pause";
        this.btnPauseResume.Click += new System.EventHandler(this.btnPauseResume_Click);
        // 
        // btnInfos
        // 
        this.btnInfos.Location = new System.Drawing.Point(115, 31);
        this.btnInfos.Size = new System.Drawing.Size(52, 20);
        this.btnInfos.Text = "Infos";
        this.btnInfos.Click += new System.EventHandler(this.btnInfos_Click);
        // 
        // mDialog
        // 
        this.mDialog.Location = new System.Drawing.Point(-1, 55);
        this.mDialog.Multiline = true;
        this.mDialog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
        this.mDialog.Size = new System.Drawing.Size(236, 144);
        // 
        // btnClear
        // 
        this.btnClear.Location = new System.Drawing.Point(171, 31);
        this.btnClear.Size = new System.Drawing.Size(60, 20);
        this.btnClear.Text = "Clear";
        this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
        // 
        // cbPolling
        // 
        this.cbPolling.Location = new System.Drawing.Point(3, 203);
        this.cbPolling.Size = new System.Drawing.Size(67, 20);
        this.cbPolling.Text = "Polling";
        // 
        // cbTCL
        // 
        this.cbTCL.Location = new System.Drawing.Point(155, 203);
        this.cbTCL.Size = new System.Drawing.Size(76, 20);
        this.cbTCL.Text = "T=CL";
        // 
        // tmrWork
        // 
        this.tmrWork.Enabled = true;
        this.tmrWork.Tick += new System.EventHandler(this.tmrWork_Tick);
        // 
        // header
        // 
        this.header.Image = ((System.Drawing.Image)(resources.GetObject("header.Image")));
        this.header.Location = new System.Drawing.Point(0, 0);
        this.header.Size = new System.Drawing.Size(240, 30);
        // 
        // branded
        // 
        this.branded.Image = ((System.Drawing.Image)(resources.GetObject("branded.Image")));
        this.branded.Location = new System.Drawing.Point(167, 237);
        this.branded.Size = new System.Drawing.Size(67, 30);
        // 
        // lbDesc
        // 
        this.lbDesc.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
        this.lbDesc.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(217)))), ((int)(((byte)(9)))), ((int)(((byte)(27)))));
        this.lbDesc.Location = new System.Drawing.Point(0, 221);
        this.lbDesc.Size = new System.Drawing.Size(232, 16);
        this.lbDesc.Text = "SpringProx SDK sample";
        this.lbDesc.TextAlign = System.Drawing.ContentAlignment.TopCenter;
        // 
        // fMain
        // 
        this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
        this.ClientSize = new System.Drawing.Size(234, 270);
        this.Controls.Add(this.branded);
        this.Controls.Add(this.cbTCL);
        this.Controls.Add(this.cbPolling);
        this.Controls.Add(this.btnClear);
        this.Controls.Add(this.mDialog);
        this.Controls.Add(this.btnInfos);
        this.Controls.Add(this.btnPauseResume);
        this.Controls.Add(this.btnOpenClose);
        this.Controls.Add(this.lbDesc);
        this.Controls.Add(this.eStatus);
        this.Controls.Add(this.header);
        this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Text = "SproxTool Sample App.";
        this.Closed += new System.EventHandler(this.fMain_Closed);

    }
#endregion

#region Windows Form Glue

    public fMain()
    {
      InitializeComponent();
    }

    protected override void Dispose(bool disposing)
    {
      base.Dispose(disposing);
    }

    private void fMain_Closed(object sender, System.EventArgs e)
    {
      if (ReaderActive)
        SPROX.ReaderClose();
    }

    static void Main()
    {
      Application.Run(new fMain());
    }

#endregion

    private void Dialog(string msg, short rc)
    {
      bool f = false;

      if ((msg != null) && (!msg.Equals("")))
      {
        mDialog.Text += msg + "\r\n";
        f = true;
      }
      if (rc != SPROX.MI_OK)
      {
        mDialog.Text += SPROX.GetErrorMessage(rc) + "\r\n";
        f = true;
      }
      
      if (!f)
      {
        mDialog.Text += "Error !"  + "\r\n";
      }
    }
    
    private void Status()
    {
      if (ReaderActive)
      {
        btnOpenClose.Text = "Close";
      } else
      {
        btnOpenClose.Text = "Open";      
      }
      
      if (ReaderPaused)
      {
        btnPauseResume.Text = "Resume";
      } else
      {
        btnPauseResume.Text = "Pause";      
      }
      
      btnPauseResume.Enabled = ReaderActive;
    }

  	private void btnOpenClose_Click(object sender, System.EventArgs e)
	  {
      short rc;

      if (ReaderActive)
      {
        Dialog("Closed", SPROX.MI_OK);
        SPROX.ReaderClose();
        ReaderActive = false;
      } else
      {
        Dialog("Opening...", SPROX.MI_OK);
        rc = SPROX.ReaderOpen(null);
        if (rc == SPROX.MI_OK)
        {
          Dialog("Opened", SPROX.MI_OK);
          ReaderActive = true;
          SPROX.ControlRF(1);
        } else
        {
          Dialog(null, rc);
        }
      }
      ReaderPaused = false;
      Status();
	  }

    private void btnPauseResume_Click(object sender, System.EventArgs e)
    {
      short rc;
      
      if (ReaderPaused)
      {
        Dialog("Resuming...", SPROX.MI_OK);
        rc = SPROX.ReaderActivate();
        if (rc == SPROX.MI_OK)
        {
          ReaderPaused = false;
        } 
        else
        {
          Dialog(null, rc);
        }
      } 
      else
      {
        Dialog("Pausing...", SPROX.MI_OK);
        rc = SPROX.ReaderDeactivate();
        if (rc == SPROX.MI_OK)
        {
          ReaderPaused = true;
        } 
        else
        {
          Dialog(null, rc);
        }       
      }
      
      Status();
    }
    
    private string ToHex(byte [] src, int len, bool reverse)
    {
      string r = "";
      int i;
      if (reverse)
      {
        for (i=len-1; i>=0; i--)
          r += String.Format("{0:X02}", src[i]);      
      } 
      else
      {
        for (i=0; i<len; i++)
          r += String.Format("{0:X02}", src[i]);
      }
      return r;
    }

    private string ToHex(byte [] src, int len)
    {
      return ToHex(src, len, false);
    }

    private void btnInfos_Click(object sender, System.EventArgs e)
    {
      short rc;
      uint dw = 0;
      byte [] uid = new byte[4];
      byte [] pid = new byte[5];
      
      Dialog("Library :", SPROX.MI_OK);
      Dialog(SPROX.GetLibrary(), SPROX.MI_OK);
      Dialog(" ", SPROX.MI_OK);
      
      if (ReaderActive && !ReaderPaused)
      {
        Dialog("Comm. device :", SPROX.MI_OK);
        Dialog(SPROX.ReaderGetDevice(), SPROX.MI_OK);
        Dialog(" ", SPROX.MI_OK);

        Dialog("Firmware :", SPROX.MI_OK);
        Dialog(SPROX.ReaderGetFirmware(), SPROX.MI_OK);
        Dialog(" ", SPROX.MI_OK);
        
        rc = SPROX.ReaderGetRc500Id(pid, uid);
        Dialog("ID :", rc);
        if (rc == SPROX.MI_OK)
          Dialog(ToHex(pid, 5) + " " + ToHex(uid, 4), SPROX.MI_OK);
      }
    }

    private void btnClear_Click(object sender, System.EventArgs e)
    {
      mDialog.Text = "";
    }

    private void tmrWork_Tick(object sender, System.EventArgs e)
    {
      short rc;
      
      byte [] atqa = new byte[2];
      byte [] atqb = new byte[11];
      byte [] uida = new byte[12];
      byte [] saka = new byte[1];
      byte [] atsa = new byte[32];
      
      byte t = 0;
      
      if (ReaderActive && !ReaderPaused)
      {
        tmrWork.Enabled = false;
        
        if (cbPolling.Checked)
        {
          rc = SPROX.B_SelectIdle(0x00, atqb);
          if (rc == SPROX.MI_OK)
          {
            Dialog("Type B card :", SPROX.MI_OK);
            Dialog(ToHex(atqb, 11), SPROX.MI_OK);
            if (cbTCL.Checked && ((atqb[9] & 0x01) != 0x00))
            {
              rc = SPROX.TclB_Attrib(atqb, 0xFF);
              if (rc == SPROX.MI_OK)
              {
                Dialog("T=CL OK", SPROX.MI_OK);
              }
              SPROX.Tcl_Deselect(0xFF);
            } else
              SPROX.B_Halt(atqb);
          }      
          if ((rc != SPROX.MI_OK) && (rc != SPROX.MI_NOTAGERR))
          {
            Dialog(null, rc);
          }
        
          t = (byte) uida.Length;
          rc = SPROX.A_SelectIdle(atqa, uida, ref t, saka);
          if (rc == SPROX.MI_OK)
          {
            Dialog("Type A card :", SPROX.MI_OK);
            Dialog(ToHex(uida, t) + " " + ToHex(atqa, 2, true) + " " + ToHex(saka, 1), SPROX.MI_OK);
            if (cbTCL.Checked && ((saka[0] & 0x20) != 0x00))
            {
              t = (byte) atsa.Length;
              rc = SPROX.TclA_GetAts(0xFF, atsa, ref t);
              if (rc == SPROX.MI_OK)
              {
                Dialog("T=CL ATS :", SPROX.MI_OK);
                Dialog(ToHex(atsa, t), SPROX.MI_OK);              
              }
              SPROX.Tcl_Deselect(0xFF);
            } else
              SPROX.A_Halt();
          }
          if ((rc != SPROX.MI_OK) && (rc != SPROX.MI_NOTAGERR))
          {
            Dialog(null, rc);
          }
        }
        
        tmrWork.Enabled = true;        
      }
    }
  }
}
